<?php
require_once 'base.php';
checkAuth();

$op = Utility::getParam('op', 'query');
if (!in_array($op, array('query', 'doQuery', 'queryPending', 'queryShipped', 'queryUnFinished',
'add', 'doAdd', 'detail', 'signShipped', 'signShippedForUnFinished', 'modify', 'doModify', 'doExport', 'doDel', 'doAddNewRemark'))) {
	die('非法操作');
}
$op();

//订单查询
function query() {
	$userInfo = $GLOBALS['userInfo'];
	$pageSize = $GLOBALS['conf']['pageSize'];
	include $GLOBALS['ROOT_PATH'] . '/views/admin/order_query.phtml';
}

function doQuery() {
	$orderSN = trim(Utility::getParam('orderSN', ''));
	$machineSN = trim(Utility::getParam('machineSN', ''));
	$orderMan = trim(Utility::getParam('orderMan', ''));
	$orderTimeBegin = trim(Utility::getParam('orderTimeBegin', ''));
	$orderTimeEnd = trim(Utility::getParam('orderTimeEnd', ''));
	$shippedTimeBegin = trim(Utility::getParam('shippedTimeBegin', ''));
	$shippedTimeEnd = trim(Utility::getParam('shippedTimeEnd', ''));
	$customerName = trim(Utility::getParam('customerName', ''));
	$orderType = (int)Utility::getParam('orderType', 99);
	$page = max((int)Utility::getParam('page', 0), 1);
	$pageSize = $GLOBALS['conf']['pageSize'];
	$start = ($page-1)*$pageSize;
	//	if (empty($orderSN) && empty($machineSN) && empty($orderMan) && empty($orderTime) && empty($customerName) && $orderType < 0) {
	//    	echoAjax(Constants::$ERR_MISSING_PARAMS);
	//    	return ;
	//    }

	$where = array();
	if (!empty($machineSN)) {
		$where['machine_sn'] = $machineSN;
	}

	if (!empty($customerName)) {
		$where['customer_name'] = $customerName;
	}

	if (!empty($orderSN)) {
		$where['sn'] = $orderSN;
	}

	if (!empty($orderMan)) {
		$where['person_name'] = $orderMan;
	}

	if ($orderType >= 0 && $orderType < 99) {
		$where['status'] = $orderType;
	}

	if (!empty($orderTimeBegin)) {
		$where['orderTimeBegin'] = $orderTimeBegin;
		if (!empty($orderTimeEnd)) {
			$where['orderTimeEnd'] = $orderTimeEnd;
		}
	}

	$userInfo = $GLOBALS['userInfo'];
	if ($userInfo['level'] > 1000) {
		if (!empty($shippedTimeBegin)) {
			$where['shippedTimeBegin'] = $shippedTimeBegin;
			if (!empty($shippedTimeEnd)) {
				$where['shippedTimeEnd'] = $shippedTimeEnd;
			}
		}
	}

	$res = Constants::$ERR_SUCCESS;
	$res['data'] = array();
	$orders = ObjectFinder::get('Order')->query($where, $start, $pageSize);
	if (empty($orders) || $orders['total']=='0') {
		echoAjax($res);
		return ;
	}

	$res['total'] = $orders['total'];
	foreach($orders['data'] as $idx=>$order) {
		$cartridges = array();
		$cartridgeInfos = explode(',', $order['cartridges_info']);
		foreach($cartridgeInfos as $info) {
			list($key, $value) = explode('_', $info);
			$cartridges[] = "{$key}({$value}) ";
		}
		$res['data'][] = array('id'=>$order['id'], 'sn'=>$order['sn'], 'customer'=>$order['customer_name'], 'cartridges'=>implode(',', $cartridges), 'time'=>$order['create_time']);
	}
	echoAjax($res);
}

/**
 * 导出订单
 *
 */
function doExport() {

	$orderSN = trim(Utility::getParam('orderSN', ''));
	$machineSN = trim(Utility::getParam('machineSN', ''));
	$orderMan = trim(Utility::getParam('orderMan', ''));
	$orderTimeBegin = trim(Utility::getParam('orderTimeBegin', ''));
	$orderTimeEnd = trim(Utility::getParam('orderTimeEnd', ''));
	$shippedTimeBegin = trim(Utility::getParam('shippedTimeBegin', ''));
	$shippedTimeEnd = trim(Utility::getParam('shippedTimeEnd', ''));
	$customerName = trim(Utility::getParam('customerName', ''));
	$orderType = (int)Utility::getParam('orderType', 99);

	$where = array();
	if (!empty($machineSN)) {
		$where['machine_sn'] = $machineSN;
	}

	if (!empty($customerName)) {
		$where['customer_name'] = $customerName;
	}

	if (!empty($orderSN)) {
		$where['sn'] = $orderSN;
	}

	if (!empty($orderMan)) {
		$where['person_name'] = $orderMan;
	}

	if ($orderType >= 0 && $orderType < 99) {
		$where['status'] = $orderType;
	}

	if (!empty($orderTimeBegin)) {
		$where['orderTimeBegin'] = $orderTimeBegin;
		if (!empty($orderTimeEnd)) {
			$where['orderTimeEnd'] = $orderTimeEnd;
		}
	}

	$userInfo = $GLOBALS['userInfo'];
	if ($userInfo['level'] > 1000) {
		if (!empty($shippedTimeBegin)) {
			$where['shippedTimeBegin'] = $shippedTimeBegin;
			if (!empty($shippedTimeEnd)) {
				$where['shippedTimeEnd'] = $shippedTimeEnd;
			}
		}
	}

	$orders = ObjectFinder::get('Order')->query($where, 0, 1000);
	if (empty($orders) || $orders['total']=='0') {
		die("没有查询结果");
	}

	$res['total'] = $orders['total'];
	foreach($orders['data'] as $idx=>$order) {
		$cartridges = array();
		$cartridgeInfos = explode(',', $order['cartridges_info']);
		foreach($cartridgeInfos as $info) {
			list($key, $value) = explode('_', $info);
			$cartridges[] = "{$key}({$value}) ";
		}
		$data[] = array(
    		'sn'=>$order['sn'], 
    		'machine_name'=>$order['machine_name'],
    		'machine_type'=>$order['machine_type'],
    		'cartridges'=>implode(',', $cartridges), 
    		'customer'=>$order['customer_name'],
    		'customer_address'=>$order['customer_address'],
    		'customer_contact'=>$order['customer_contact'],
    		'time'=>$order['create_time'],
    		'express_name'=>$order['express_name'],
    		'express_id'=>$order['express_id']	
		);
	}

	$fileName =  date('YmdHis') . '.xls';
	$filePath = $GLOBALS['conf']['export_excel_path'];
	$fileFullPath = $filePath . $fileName;
	if (!file_exists($filePath)) {
		mkdir($filePath, 0777);
	}

	$head = "订单号\t机器名称\t机器型号\t耗材型号及个数\t用户信息\t详细地址\t联系人\t下单时间\t快递公司\t快递单号\n";
	file_put_contents($fileFullPath, iconv('utf-8', 'gbk', $head));
	foreach($data as $item) {
		file_put_contents($fileFullPath, iconv('utf-8', 'gbk', implode("\t", $item))."\n", FILE_APPEND);
	}
	header("location:{$GLOBALS['conf']['download_path']}{$fileName}");
}

//待发订单查询
function queryPending() {
	$conf = $GLOBALS['conf'];
	$page = (int)Utility::getParam('page', 1);
	$start = (max($page, 1)-1)*$conf['pageSize'];
	$ordersInfo = ObjectFinder::get('Order')->getList(array('status'=>0), $start, $conf['pageSize']);
	foreach($ordersInfo['data'] as $order) {
		$customerNamesInfo[$order['id']] = $order['customer_name'];
	}

	include $GLOBALS['ROOT_PATH'] . '/views/admin/order_queryPending.phtml';
}

/**
 * 已发订单查询
 * 包含全部发货和部分发货订单
 *
 */
function queryShipped() {

	$conf = $GLOBALS['conf'];
	$page = (int)Utility::getParam('page', 1);
	$start = (max($page, 1)-1)*$conf['pageSize'];
	//$ordersInfo = ObjectFinder::get('Order')->getList(array('status'=>1), $start, $conf['pageSize']);
	$ordersInfo = ObjectFinder::get('Order')->getShippedList($start, $conf['pageSize']);
	foreach($ordersInfo['data'] as $order) {
		$customerNamesInfo[$order['id']] = $order['customer_name'];
	}

	include $GLOBALS['ROOT_PATH'] . '/views/admin/order_queryShipped.phtml';
}
/**
 * 部分发货订单查询
 *
 */
function queryUnFinished() {
	$conf = $GLOBALS['conf'];
	$page = (int)Utility::getParam('page', 1);
	$start = (max($page, 1)-1)*$conf['pageSize'];
	$ordersInfo = ObjectFinder::get('Order')->getList(array('status'=>1), $start, $conf['pageSize']);
	foreach($ordersInfo['data'] as $order) {
		$customerNamesInfo[$order['id']] = $order['customer_name'];
	}

	include $GLOBALS['ROOT_PATH'] . '/views/admin/order_queryUnFinished.phtml';
}

/**
 * 新建订单
 *
 */
function add() {

	$SN = ObjectFinder::get('Order')->genOrderSN();
	$machines = ObjectFinder::get('Machine')->getList();
	$customerList = ObjectFinder::get('CustomerIndex')->getList(array('pid'=>0));
	$warehouse = $GLOBALS['conf']['warehouse'];

	include $GLOBALS['ROOT_PATH'] . '/views/admin/order_add.phtml';
}

function doAdd() {
	//		'sn':orderSN,
	//		'orderMan':orderMan,
	//		'customerName':getSelectText('customerInfoSelect')+"("+getSelectText('childNameSelect')+")",
	//		'area':province+'_'+city+'_'+area,
	//		'address':address,
	//		'zipcode':zipcode,
	//		'contact':contact,
	//		'tel':tel,
	//		'email':email,
	//		'machineName':machineName,
	//		'machineType':machineType,
	//		'machineSN':machineSN,
	//		'cartridgeCountInfo':cartridgeCountInfo

	$sn = trim(Utility::getParam('sn', ''));
	$personName = trim(Utility::getParam('orderMan', ''));
	$customerName = trim(Utility::getParam('customerName', ''));
	$customerArea = trim(Utility::getParam('area', ''));
	$customerAddress = trim(Utility::getParam('address', ''));
	$customerZipcode = trim(Utility::getParam('zipcode', ''));
	$customerContact = trim(Utility::getParam('contact', ''));
	$customerTel = trim(Utility::getParam('tel', ''));
	$customerEmail = trim(Utility::getParam('email', ''));
	$machineName = trim(Utility::getParam('machineName', ''));
	$machineSN = trim(Utility::getParam('machineSN', ''));
	$machineType = trim(Utility::getParam('machineType', ''));
	$cartridgesInfo = trim(Utility::getParam('cartridgeCountInfo', ''));

	if (empty($sn) || empty($personName) || empty($customerName) || empty($customerArea) || empty($customerAddress) || empty($customerContact) || empty($customerTel) || empty($machineName) || empty($machineSN) || empty($cartridgesInfo)){
		echoAjax(Constants::$ERR_MISSING_PARAMS);
		return ;
	}

	$data = array(
		'sn'=>$sn,
		'person_name'=>$personName,
		'customer_name'=>$customerName,
		'customer_area'=>$customerArea,
		'customer_address'=>$customerAddress,
		'customer_zipcode'=>$customerZipcode,
		'customer_contact'=>$customerContact,
		'customer_tel'=>$customerTel,
		'customer_email'=>$customerEmail,
		'machine_name'=>$machineName,
		'machine_sn'=>$machineSN,
		'machine_type'=>empty($machineType) ? '' : $machineType , 
		'cartridges_info'=>$cartridgesInfo,
	);
	$res = ObjectFinder::get('Order')->add($data);
	echoAjax($res ? Constants::$ERR_SUCCESS : Constants::$ERR_FAILED);
}

/**
 * 查看详情
 *
 */
function detail() {

	$id = (int)Utility::getParam('id', 0);
	$from = Utility::getParam('from', 'pending');
	if (empty($id)) {
		echo Constants::$ERR_MISSING_PARAMS['errmsg'];
		return;
	}

	$orderInfo = ObjectFinder::get('Order')->getInfoById($id);
	if (empty($orderInfo)) {
		echo Constants::$ERR_INVALID_PARAMS['errmsg'];
		return;
	}
	$orderInfo = $orderInfo[0];
	$userInfo = $GLOBALS['userInfo'];
	$expressList = ObjectFinder::get('Express')->getList();
	include $GLOBALS['ROOT_PATH'] . '/views/admin/order_detail.phtml';
}

/**
 * 标记发货
 *
 */
function signShipped() {

	$id = (int)Utility::getParam('id', 0);
	$shippedTime = trim(Utility::getParam('shipped_time', ''));
	$expressName = trim(Utility::getParam('express_name', ''));
	$expressTel = trim(Utility::getParam('express_tel', ''));
	$expressID = trim(Utility::getParam('express_id', ''));
	$remark = trim(Utility::getParam('remark', ''));
	$shippedStatus = (int)Utility::getParam('shipped_status', 1);
	$shippedRemark = trim(Utility::getParam('shipped_remark', ''));
	if (empty($id) || empty($expressID) || empty($expressName)) {
		echoAjax(Constants::$ERR_MISSING_PARAMS);
		return;
	}
	
	$orderInfo = ObjectFinder::get('Order')->getInfoById($id);
	if (empty($orderInfo)) {
		echoAjax(Constants::$ERR_INVALID_PARAMS);
		return;
	}
	if ($orderInfo[0]['status'] > 1) {
		echoAjax(Constants::$ERR_ORDER_SHIPPED);
		return;
	}
	
	$remark = $orderInfo[0]['remark'] . formatRemark($remark);
	$res = ObjectFinder::get('Order')->signShippedById($id, $expressName, $expressTel, $expressID, $shippedTime, $remark, $shippedStatus, $shippedRemark);
	echoAjax($res ? Constants::$ERR_SUCCESS : Constants::$ERR_FAILED);
}

function signShippedForUnFinished() {
	$id = (int)Utility::getParam('id', 0);
	$shippedStatus = (int)Utility::getParam('shipped_status', 1);
	$shippedRemark = trim(Utility::getParam('shipped_remark', ''));
	$remark = trim(Utility::getParam('remark', ''));
	
	if (empty($id)) {
		echoAjax(Constants::$ERR_MISSING_PARAMS);
		return;
	}
	$orderInfo = ObjectFinder::get('Order')->getInfoById($id);
	if (empty($orderInfo)) {
		echoAjax(Constants::$ERR_INVALID_PARAMS);
		return;
	}
	if ($orderInfo[0]['status'] > 1) {
		echoAjax(Constants::$ERR_ORDER_SHIPPED);
		return;
	}

	$remark = $orderInfo[0]['remark'] . formatRemark($remark);
	$res = ObjectFinder::get('Order')->signShippedForUnFinishedById($id, $shippedStatus, $shippedRemark, $remark);
	//echoAjax($res ? Constants::$ERR_SUCCESS : Constants::$ERR_FAILED);
	echoAjax(Constants::$ERR_SUCCESS);
}

/**
 * 修改订单
 *
 */
function modify() {

	$id = max(0, (int)Utility::getParam('id', 0));
	if (empty($id)) {
		echo Constants::$ERR_MISSING_PARAMS['errmsg'];
		return ;
	}

	$orderInfo = ObjectFinder::get('Order')->getInfoById($id);
	if (empty($orderInfo)) {
		echo Constants::$ERR_QUERY_ORDER_NOT_EXIST['errmsg'];
		return ;
	}

	$orderInfo = $orderInfo[0];
	if ($orderInfo['status'] == 1) {
		echo Constants::$ERR_ORDER_SHIPPED_CANOT_MODIFY['errmsg'];
		return ;
	}

	$machineInfo = ObjectFinder::get('Machine')->getInfoByName($orderInfo['machine_name']);
	if (empty($machineInfo)) {
		echoAjax(Constants::$ERR_QUERY_MACHINE_NOT_EXIST);
		return ;
	}

	$types = explode(',', $machineInfo['cartridges_type']);
	foreach($types as $type) {
		$res = ObjectFinder::get('Cartridge')->queryByType($type);
		if (empty($res)) {
			$inventorys[$type] = $res;
		}else {
			$inventorys[$type]['inventory'] = json_decode($res[0]['inventory']);
		}
	}

	$machines = ObjectFinder::get('Machine')->getList();
	$warehouse = $GLOBALS['conf']['warehouse'];

	include $GLOBALS['ROOT_PATH'] . '/views/admin/order_modify.phtml';
}

function doModify() {

	$id = (int)Utility::getParam('id', 0);
	$customerArea = trim(Utility::getParam('area', ''));
	$customerAddress = trim(Utility::getParam('address', ''));
	$customerZipcode = trim(Utility::getParam('zipcode', ''));
	$customerContact = trim(Utility::getParam('contact', ''));
	$customerTel = trim(Utility::getParam('tel', ''));
	$customerEmail = trim(Utility::getParam('email', ''));
	$machineName = trim(Utility::getParam('machineName', ''));
	$machineSN = trim(Utility::getParam('machineSN', ''));
	$machineType = trim(Utility::getParam('machineType', ''));
	$cartridgesInfo = trim(Utility::getParam('cartridgeCountInfo', ''));
	$remark = trim(Utility::getParam('remark', ''));

	if (empty($id) || empty($customerArea) || empty($customerAddress) || empty($customerContact) || empty($customerTel) || empty($machineName) || empty($machineSN) || empty($cartridgesInfo)){
		echoAjax(Constants::$ERR_MISSING_PARAMS);
		return ;
	}
	
	$orderInfo = ObjectFinder::get('Order')->getInfoById($id);
	if (empty($orderInfo)) {
		echo Constants::$ERR_INVALID_PARAMS['errmsg'];
		return;
	}
	$remark = $orderInfo[0]['remark'] . formatRemark($remark);

	$data = array(
		'customer_area'=>$customerArea,
		'customer_address'=>$customerAddress,
		'customer_zipcode'=>$customerZipcode,
		'customer_contact'=>$customerContact,
		'customer_tel'=>$customerTel,
		'customer_email'=>$customerEmail,
		'machine_name'=>$machineName,
		'machine_sn'=>$machineSN,
		'machine_type'=>empty($machineType) ? '' : $machineType,
		'cartridges_info'=>$cartridgesInfo,
		'remark'=>$remark,
	);
	$res = ObjectFinder::get('Order')->modify($data, array('id'=>$id));
	echoAjax(Constants::$ERR_SUCCESS);
}

/**
 * 订单删除
 *
 */
function doDel() {
	$id = (int)Utility::getParam('id', 0);
	if (empty($id)) {
		echoAjax(Constants::$ERR_MISSING_PARAMS);
		return ;
	}

	$res = ObjectFinder::get('Order')->delete(array('id'=>$id));
	echoAjax($res ? Constants::$ERR_SUCCESS : Constants::$ERR_FAILED);
}

function formatRemark($content) {
	if (empty($content)) {
		return "";
	}
	return '<p><span class="remarkTime">' . date('Y-m-d H:i:s') . '</span><br/><span class="remarkContent">' . $content . '</span></p>';
}

function doAddNewRemark() {
	$id = (int)Utility::getParam('id', 0);
	$remark = trim(Utility::getParam('remark', ''));

	if (empty($id) || empty($remark)){
		echoAjax(Constants::$ERR_MISSING_PARAMS);
		return ;
	}
	
	$orderInfo = ObjectFinder::get('Order')->getInfoById($id);
	if (empty($orderInfo)) {
		echo Constants::$ERR_INVALID_PARAMS['errmsg'];
		return;
	}
	$remark = $orderInfo[0]['remark'] . formatRemark($remark);

	$data = array(
		'remark'=>$remark,
	);
	$res = ObjectFinder::get('Order')->modify($data, array('id'=>$id));
	echoAjax(Constants::$ERR_SUCCESS);
}
?>